package com.ax.center.aspect;

import com.ax.center.annotation.Logging;
import com.ax.center.entity.Operation;
import com.ax.center.service.OperationService;
import com.ax.center.urils.TimeUtils;
import com.ax.center.urils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

/**
 * @author zy
 * @date 2023/7/4 9:16
 */

@Component
@Aspect
@Slf4j
public class LogAspect {
    @Autowired
    private OperationService operationService;

    @Pointcut("@annotation(com.ax.center.annotation.Logging)")
    public void pt(){
    }
    @Around("pt()")
    public Object storeLog(ProceedingJoinPoint joinPoint) {
        try {

            Object result = joinPoint.proceed();
            String nickName = UserHolder.getUser().getName();
            long id= UserHolder.getUser().getStaffId();
            Date date = new Date();
            String nowTime = TimeUtils.getStartOfData(date);
            //获取被增强方法上的用户对象
            Logging systemLog = getSystemLog(joinPoint);
            //获取描述信息
            String description = systemLog.description();
            Operation operation = new Operation();
            operation.setDescription(description)
                    .setLevel(1)
                    .setStaffId(id)
                    .setGmtCreate(nowTime)
                    .setResult(result.toString())
                    .setOpName(nickName);
            operationService.insert(operation);
            //拼接
            String logEntry= nowTime+" "+id+" "+nickName+" "+description+" "+result.toString();
            //打印
            writeLog("D:\\IDEA_codes\\PermissionCenter\\src\\main\\resources\\logfile.log",logEntry);
            return result;
        } catch (Throwable e) {
            throw new RuntimeException(e);
        }
    }
    private Logging getSystemLog(ProceedingJoinPoint joinPoint) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Logging systemLog = methodSignature.getMethod().getAnnotation(Logging.class);
        return systemLog ;
    }
    public void writeLog( String filePath, String logEntry){
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            writer.write(logEntry);
            writer.newLine();
          log.info("操作日志已写入文件: " + filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



}
